package com.gid.rcflightlogger;

import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

import com.orm.androrm.Filter;

public class AircraftEditActivity extends BaseActivity {
	
	//db objects
	private Aircraft mAircraft = null;
	private Flight mFlight = null;

	public static final int INVALID_ID = 0;
	private int mID = INVALID_ID;
	
	//form objects
	private EditText mName;
	private Spinner mType;
	private EditText mBuildDate;
	private EditText mExistingFlights;
	private EditText mExistingFlightMinutes;
	private CheckBox mStatus;
	private Button mSave;
	private Button mDelete;
	
	//dialog ids
	public static final int DIALOGID_BUILDDATE = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_aircraftedit); 
        mName = (EditText) findViewById(R.id.aircraftedit_input_name);
        mType = (Spinner) findViewById(R.id.aircraftedit_spinner_type);
        mBuildDate = (EditText) findViewById(R.id.aircraftedit_input_builddate);
        mExistingFlights = (EditText) findViewById(R.id.aircraftedit_input_flights);
        mExistingFlightMinutes = (EditText) findViewById(R.id.aircraftedit_input_flightmins);
        mStatus = (CheckBox) findViewById(R.id.aircraftedit_input_status);
        mSave = (Button) findViewById(R.id.aircraftedit_btn_save);
        mDelete = (Button) findViewById(R.id.aircraftedit_btn_delete);
        mType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Aircraft.TYPE_ARRAY));

        //check if we are doing an add or edit
        if (savedInstanceState != null)
        {
        	mID = savedInstanceState.getInt(Aircraft.ID_LABEL, INVALID_ID);
        }
        
        if (mID == INVALID_ID) {
        	mID = getIntent().getIntExtra(Aircraft.ID_LABEL, INVALID_ID);
        }
        
        //myUtils.makeToast(getApplicationContext(), "received id = " + mID);

        //by this stage, invalid mID means we are creating a new entry
        if (mID == INVALID_ID)
        {
        	//add aircraft
        	mAircraft = new Aircraft();
        	mFlight = new Flight();
        	mFlight.setFake(true);
        	mFlight.setCount(0);
        	mFlight.setAircraft(mAircraft);
        	mSave.setText(" Add ");
        	mSave.setVisibility(View.VISIBLE);
        	this.setTitle("Adding New Aircraft");
        }
        else
        {	
        	//edit existing one
        	this.setTitle("Updating Aircraft");
        	mAircraft = Aircraft.objects(getApplicationContext()).get(mID);
        	if (mAircraft == null)
        	{
        		//error condition
        		setResult(RESULT_FIRST_USER);
        		finish();
        	}
        	Filter filter = new Filter();
        	filter.is("mAircraft", mAircraft).is("mFake", 1);
        	List<Flight> ffs = Flight.objects(getApplicationContext()).filter(filter).toList();
        	if (!ffs.isEmpty())
        	{
        		mFlight = ffs.get(0);
        	}
        	else
        	{
        		mFlight = new Flight();
        		mFlight.setFake(true);
        		mFlight.setAircraft(mAircraft);
        	}
        	mSave.setText("Update");
        	mSave.setVisibility(View.VISIBLE);
        	mDelete.setVisibility(View.VISIBLE);
        	mDelete.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AlertDialog.Builder builder = new AlertDialog.Builder(AircraftEditActivity.this);
					builder.setMessage("Delete this aircraft?").setCancelable(false);
					builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							mAircraft.delete(getApplicationContext());
							setResult(RESULT_OK);
			        		finish();
						}
					});
					builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
	        	    AlertDialog alert = builder.create();
	        	    alert.show();
				}
			});
        }
        
        //Register listeners  
        //1- trigger date picker dialog on date field, need both touch event and key event for keyboard and touch UI      
        mBuildDate.setOnTouchListener(new EditText.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent e) {
				showDialog(DIALOGID_BUILDDATE);
				return true;
			}
        });
        mBuildDate.setOnKeyListener(new View.OnKeyListener(){

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				showDialog(DIALOGID_BUILDDATE);
				return true;
			}
        	
        });
        
        //2- trigger db save on button
        mSave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (saveData())
					setResult(RESULT_FIRST_USER);
				else
					setResult(RESULT_OK);
				finish();
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog diag;
		switch (id) {
		case DIALOGID_BUILDDATE:
			Date date = myUtils.Str2Date(mBuildDate.getText().toString());
			DatePickerDialog.OnDateSetListener datesetsistener = new DatePickerDialog.OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					mBuildDate.setText(myUtils.Date2Str(year, monthOfYear, dayOfMonth));
				}
			};
			//myUtils.makeToast(getApplicationContext(), "date string = " + mBuildDate.getText().toString()); 
			diag = new DatePickerDialog(this, datesetsistener, date.getYear() + 1900, date.getMonth(), date.getDate());
			return diag;
		}
		return null; 
	}
	
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mID != INVALID_ID)
        	outState.putSerializable(Aircraft.ID_LABEL, mID);
        
        outState.putSerializable(Aircraft.ID_LABEL, (int)mID);
    }
    
    //load data from mAircraft object into form
	private void loadData() {
		mName.setText(mAircraft.getName());
		String type = mAircraft.getType();
		for (int i = 0; i< Aircraft.TYPE_ARRAY.length; i++)
		{
			if (Aircraft.TYPE_ARRAY[i].equals(type))
			{
				mType.setSelection(i);
				break;
			}
		}

		mBuildDate.setText(myUtils.Date2Str(mAircraft.getBuildDate()));
		mExistingFlights.setText(Integer.toString(mFlight.getCount()));
		mExistingFlightMinutes.setText(Integer.toString(mFlight.getDuration()/60));
		mStatus.setChecked(mAircraft.getStatus());
	}
	
	//save data from form into database
	private boolean saveData()
	{
		mAircraft.setName(mName.getText().toString());
		mAircraft.setType((String)mType.getSelectedItem());
		//myUtils.makeToast(getApplicationContext(), mAircraft.getType());
		mAircraft.setBuildDate(myUtils.Str2Date(mBuildDate.getText().toString()));
		mAircraft.setStatus(mStatus.isChecked());
		boolean asave = mAircraft.save(getApplicationContext());
		
		mFlight.setCount(Integer.parseInt(mExistingFlights.getText().toString()));
		mFlight.setDuration(Integer.parseInt(mExistingFlightMinutes.getText().toString())*60); //we store flight duration in seconds in db
		mFlight.setAircraft(mAircraft);
		boolean fsave = mFlight.save(getApplicationContext());
		
		return (asave && fsave);
	}
}
